import 'dart:async';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import '../widgets/AudioWaveform.dart';

class AudioWaveformDemo extends StatefulWidget {
  const AudioWaveformDemo({Key? key}) : super(key: key);

  @override
  State<AudioWaveformDemo> createState() => _AudioWaveformDemoState();
}

class _AudioWaveformDemoState extends State<AudioWaveformDemo> {
  List<double> _amplitudes = [];
  bool _isRecording = false;
  late Timer _timer;

  @override
  void initState() {
    super.initState();
    // 模拟音频数据
    _simulateAudioData();
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  // 模拟音频数据变化
  void _simulateAudioData() {
    _timer = Timer.periodic(const Duration(milliseconds: 150), (timer) {
      if (!_isRecording) return;

      setState(() {
        // 生成随机振幅数据，模拟音频输入
        _amplitudes = List.generate(50, (index) {
          // 生成0-15000之间的随机振幅（模拟16位PCM数据）
          return Random().nextDouble() * 15000;
        });
      });
    });
  }

  // 开始/停止模拟录音
  void _toggleRecording() {
    setState(() {
      _isRecording = !_isRecording;
      if (!_isRecording) {
        _amplitudes = []; // 停止时清空波形
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('音频波形可视化'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 使用自定义的音频波形组件
            AudioWaveform(
              amplitudes: _amplitudes,
              height: 30,
              width: MediaQuery.of(context).size.width * 0.8,
              waveColor: _isRecording ? Colors.blue : Colors.grey,
            ),

            const SizedBox(height: 40),

            ElevatedButton(
              onPressed: _toggleRecording,
              child: Text(
                _isRecording ? '停止录音' : '开始录音',
                style: const TextStyle(fontSize: 18),
              ),
              style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 15),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(30),
                ),
              ),
            ),

            const SizedBox(height: 20),

            if (_isRecording)
              const Text(
                '正在模拟音频输入...',
                style: TextStyle(color: Colors.grey),
              )
            else
              const Text(
                '点击开始按钮查看波形效果',
                style: TextStyle(color: Colors.grey),
              ),
          ],
        ),
      ),
    );
  }
}